package logic

import (
	"Junior_two/subject/usercenter/userrpc/pb/user"
	"context"
	"github.com/astaxie/beego/validation"
	"net/http"

	"Junior_two/subject/usercenter/userapi/internal/svc"
	"Junior_two/subject/usercenter/userapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthLogic {
	return &AuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AuthLogic) Auth(req *types.AuRequest) (resp *types.AuResponse, err error) {
	// todo: add your logic here and delete this line

	valid := validation.Validation{}

	valid.Required(req.RealName, "realName").Message("真实姓名不能为空")
	valid.Required(req.IdCard, "idCard").Message("身份证不能为空")
	valid.Length(req.IdCard, 18, "idCard").Message("身份证格式不正确")
	if valid.HasErrors() {
		for _, v := range valid.Errors {
			return &types.AuResponse{
				Msg:  v.Message,
				Code: http.StatusAccepted,
			}, nil
		}
	}
	res, err := l.svcCtx.UserServer.Auth(l.ctx, &user.AuRequest{
		RealName: req.RealName,
		IdCard:   req.IdCard,
	})
	if err != nil {
		return &types.AuResponse{
			Msg:  err.Error(),
			Code: http.StatusCreated,
		}, nil
	}
	if res.Code != http.StatusOK {
		return &types.AuResponse{
			Msg:  res.Msg,
			Code: res.Code,
		}, nil
	}
	return &types.AuResponse{
		Msg:  res.Msg,
		Code: res.Code,
	}, nil
}
